<template>
  <el-container class="scoring-container">
    <!-- 侧边栏 -->
    <el-aside class="sidebar">
      <el-menu
        :default-active="activeSection"
        @select="activeSection = $event"
        class="menu"
      >
        <el-menu-item index="myScore">我的分数</el-menu-item>
        <el-menu-item index="peerReview">小组互评</el-menu-item>
        <el-menu-item index="appeal">我要申诉</el-menu-item>
      </el-menu>
    </el-aside>

    <!-- 右侧内容区 -->
    <el-main class="content">
      <div class="board">
        <!-- 我的分数页面 -->
        <div v-if="activeSection === 'myScore'" class="section">
          <h2>我的分数</h2>
          <el-card class="score-card">
            <p><strong>任务质量分：</strong>{{ myScore.quality }}</p>
            <p><strong>参与积极性分：</strong>{{ myScore.engagement }}</p>
            <p><strong>协商分：</strong>{{ myScore.negotiate }}</p>
            <p><strong>准时完成分：</strong>{{ myScore.on_time }}</p>
            <p><strong>重组意愿分：</strong>{{ myScore.rematch_willingness }}</p>
          </el-card>
          <el-divider></el-divider>
          <!-- 图表展示区域 -->
          <div id="scoreChart" class="chart-container"></div>
        </div>

        <!-- 小组互评页面 -->
        <div v-if="activeSection === 'peerReview'" class="section">
          <h2>小组互评</h2>
          <div v-if="peerReviewList.length === 0">
            <p>暂无更多成员</p>
          </div>
          <div v-else>
            <p>请为组内其他成员进行评分：</p>
            <el-form :model="peerReviewForm" label-width="180px">
              <div
                v-for="(member, index) in peerReviewList"
                :key="member.user_id"
                class="member-review"
              >
                <el-card class="member-card">
                  <h3>{{ member.username }}</h3>
                  <el-form-item label="重组意愿分">
                    <el-input-number
                      v-model="peerReviewForm[member.user_id].rematch_willingness"
                      :min="0"
                      :max="100"
                    />
                  </el-form-item>
                  <el-form-item label="参与积极性分">
                    <el-input-number
                      v-model="peerReviewForm[member.user_id].engagement"
                      :min="0"
                      :max="100"
                    />
                  </el-form-item>
                  <el-form-item label="协商分">
                    <el-input-number
                      v-model="peerReviewForm[member.user_id].negotiate"
                      :min="0"
                      :max="100"
                    />
                  </el-form-item>
                </el-card>
              </div>
              <el-button type="primary" @click="submitPeerReview">提交互评分</el-button>
            </el-form>
          </div>
        </div>

        <!-- 我要申诉页面 -->
        <div v-if="activeSection === 'appeal'" class="section">
          <h2>我要申诉</h2>
          <el-form :model="appealForm" label-width="150px">
            <el-form-item label="申诉理由">
              <el-input
                type="textarea"
                v-model="appealForm.reason"
                placeholder="请输入申诉理由..."
                rows="5"
              />
            </el-form-item>
            <el-button type="primary" @click="submitAppeal">提交申诉</el-button>
          </el-form>
        </div>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import { defineComponent, ref, onMounted, nextTick } from "vue";
import { useRouter } from "vue-router";
import {
  ElContainer,
  ElAside,
  ElMain,
  ElMenu,
  ElMenuItem,
  ElCard,
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElButton,
  ElDivider,
} from "element-plus";
import axios from "@/axiosInstance";
import * as echarts from "echarts";

export default defineComponent({
  name: "ScoringPage",
  components: {
    ElContainer,
    ElAside,
    ElMain,
    ElMenu,
    ElMenuItem,
    ElCard,
    ElForm,
    ElFormItem,
    ElInput,
    ElInputNumber,
    ElButton,
    ElDivider,
  },
  setup() {
    const router = useRouter();
    // 从路由 query 获取参数
    const taskId = ref(null);
    const groupId = ref(null);
    const sysUserId = ref(null);
    const sysUserName = ref(null);

    // 当前激活的侧边栏选项，默认 "myScore"
    const activeSection = ref("myScore");

    // 我的分数数据，从后端获取
    const myScore = ref({
      quality: 0,
      engagement: 0,
      negotiate: 0,
      on_time: 0,
      rematch_willingness: 0,
    });

    // 小组互评分表单（以目标成员ID为键）
    const peerReviewList = ref([]);
    const peerReviewForm = ref({});

    // 申诉表单
    const appealForm = ref({ reason: "" });

    onMounted(() => {
      const params = new URLSearchParams(window.location.search);
      taskId.value = params.get("taskId");
      groupId.value = params.get("groupId");
      sysUserId.value = params.get("sysUserId");
      sysUserName.value = params.get("sysUserName");
      console.log(
        "参数：",
        taskId.value,
        groupId.value,
        sysUserId.value,
        sysUserName.value
      );
      fetchMyScore();
      fetchGroupMembers();
    });

    // 获取当前学生的分数数据
    const fetchMyScore = async () => {
      try {
        const response = await axios.get("http://39.105.217.183:8000/api/my-score/", {
          params: {
            task_id: taskId.value,
            sysUserId: sysUserId.value,
            group_id: groupId.value,
          },
        });
        if (response.data && response.data.score) {
          myScore.value = response.data.score;
          nextTick(() => {
            initScoreChart();
          });
        }
      } catch (error) {
        console.error("获取我的分数失败:", error);
      }
    };

    // 获取当前小组成员名单（排除当前学生）
    const fetchGroupMembers = async () => {
      try {
        const response = await axios.get("http://39.105.217.183:8000/api/score/group_members/", {
          params: {
            task_id: taskId.value,
            group_id: groupId.value,
          },
        });
        const members = response.data; // 假设返回数组，每个对象包含 user_id 和 username
        console.log("小组成员：", members);
        peerReviewList.value = members.filter(
          (member) => member.user_id != sysUserId.value
        );
        // 初始化互评分表单数据
        peerReviewList.value.forEach((member) => {
          peerReviewForm.value[member.user_id] = {
            rematch_willingness: 0,
            engagement: 0,
            negotiate: 0,
          };
        });
      } catch (error) {
        console.error("获取小组成员失败:", error);
      }
    };

    // 使用 ECharts 绘制分数图表
    const initScoreChart = () => {
      const chartDom = document.getElementById("scoreChart");
      if (!chartDom) return;
      const myChart = echarts.init(chartDom);
      const option = {
        title: {
          text: "各维度得分",
          left: "center",
        },
        tooltip: {},
        xAxis: {
          type: "category",
          data: [
            "任务质量",
            "参与积极性",
            "协商分",
            "准时完成",
            "重组意愿",
          ],
        },
        yAxis: {
          type: "value",
          min: 0,
          max: 100,
        },
        series: [
          {
            name: "分数",
            type: "bar",
            data: [
              myScore.value.quality,
              myScore.value.engagement,
              myScore.value.negotiate,
              myScore.value.on_time,
              myScore.value.rematch_willingness,
            ],
            itemStyle: {
              color: "#409EFF",
            },
          },
        ],
      };
      myChart.setOption(option);
    };

    // 提交小组互评分
    const submitPeerReview = async () => {
      try {
        const payload = {
          task_id: taskId.value,
          group_id: groupId.value,
          reviews: peerReviewForm.value,
          sysUserId: sysUserId.value,
          sysUserName: sysUserName.value,
        };
        console.log("提交小组互评分：", payload);
        // 调用后端接口
        await axios.post("http://39.105.217.183:8000/api/peer-review/", payload);
        alert("互评分已提交！");
      } catch (error) {
        console.error("提交互评分失败:", error);
        alert("提交互评分失败！");
      }
    };

    // 提交申诉
    const submitAppeal = async () => {
      try {
        const payload = {
          task_id: taskId.value,
          sysUserId: sysUserId.value,
          group_id: groupId.value,
          reason: appealForm.value.reason,
        };
        console.log("提交申诉：", payload);
        // 调用后端接口提交申诉
        await axios.post("http://39.105.217.183:8000/api/appeal/", payload);
        alert("申诉已提交，请等待老师回复！");
      } catch (error) {
        console.error("提交申诉失败:", error);
        alert("提交申诉失败！");
      }
    };

    return {
      activeSection,
      myScore,
      peerReviewList,
      peerReviewForm,
      appealForm,
      taskId,
      groupId,
      sysUserId,
      sysUserName,
      fetchMyScore,
      fetchGroupMembers,
      initScoreChart,
      submitPeerReview,
      submitAppeal,
    };
  },
});
</script>

<style scoped>
.scoring-container {
  min-height: 100vh;
  display: flex;
}

.sidebar {
  width: 220px;
  background-color: #f5f5f5;
  padding-top: 20px;
  border-right: 1px solid #ebeef5;
}

.menu {
  border-right: none;
}

.content {
  padding: 20px;
  flex: 1;
  display: flex;
  justify-content: center;
}

.board {
  width: 800px; /* 固定宽度的板 */
  background-color: #ffffff;
  padding: 20px;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.section {
  margin-bottom: 20px;
}

.score-card {
  padding: 20px;
  margin-top: 10px;
}

.chart-container {
  width: 100%;
  height: 400px;
  margin-top: 20px;
}

.member-review {
  margin-bottom: 20px;
}

.member-card {
  padding: 15px;
}
</style>